﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AppBrowser.Common;

namespace AppBrowser
{
    public partial class frmAppBrowser : Form
    {
        public AppData data;
        private bool _AllowEdit;
        public bool AllowEdit
        {
            get { return _AllowEdit; }
            set { 
                _AllowEdit = value;
                Properties.Settings.Default.AppBrowserEdit = value;
                EnableEditingFunctions(_AllowEdit);
            }
        }
        // array of controls that contain editing functionality
        public Object[] EditControls;


        public class SelectedApps
        {
            public string App_Id;
            public int SelectedVersionIndex;

            public SelectedApps(string appid, int versionindex)
            {
                App_Id = appid;
                SelectedVersionIndex = versionindex;
            }
        }

        private frmDownloadApps DownloadForm;
        
        /// <summary>
        /// Applications that have been checked, to prepare for download
        /// </summary>
        public Dictionary<string, SelectedApps> SelectedAppList = new Dictionary<string, SelectedApps>();


        public frmAppBrowser()
        {
            InitializeComponent();
        }

        private Version GetCurrentVersion()
        {
            // get version info
            // get the version object for this assembly
            Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            return v;
        }

        private void frmAppBrowser_Load(object sender, EventArgs e)
        {
            

            StatusLabel.Text = "Loading Database..";
            data = new AppData();
            // toolsToolStripMenuItem.ImageScalingSize;


            Version v = GetCurrentVersion();
            this.Text += "BETA Version: " + v.Major + "." + v.Minor + " (Build: " + v.Build + ")"
                + " Database : " + data.GetDatabaseDate();
            
            
            StatusLabel.Text = "Scanning Installed Applications....";
            InstalledApps.QueryInstalledApps();


            StatusLabel.Text = "Loading Categories...";
            FillCategories(data.GetCategories().Rows);
            // FillAppList(data.GetAppsByCategory(listView1.Items[0].SubItems[1].Text.ToString()));

            StatusLabel.Text = "Preparing Filters..";
            FillFilterList();

            StatusLabel.Text = "Loading Application List..";
            BuildAppView();
            // data.SaveXML();

            // set up list of controls that provide editing
            EditControls = new Object[] {  
                                            this.btnAddCategory, btnEditCategory, 
                                            
                                            toolStripBtnAdd, toolStripBtnEdit, toolStripBtnDelete
            };

            

            try
            {
                this.AllowEdit = Properties.Settings.Default.AppBrowserEdit;
            }
            catch
            {
                this.AllowEdit = false;
            }

            StatusLabel.Text = "Ready";
        }

        /// <summary>
        /// Enable/Disable all editing functions
        /// Add Item
        /// Edit Item
        /// Delete Item
        /// Add/Edit/Delete Category
        /// Save
        /// </summary>
        /// <param name="enable"></param>
        private void EnableEditingFunctions(bool enable)
        {
            foreach (Object ctl in EditControls)
            {
                if (ctl.GetType() == typeof(System.Windows.Forms.Button))
                {
                    Button aControl = (Button)ctl;

                    aControl.Enabled = enable;
                    aControl.Visible = enable;          
                
                }
                else
                {
                    if (ctl.GetType() == typeof(System.Windows.Forms.ToolStripButton))
                    {
                        ToolStripButton aControl = (ToolStripButton)ctl;
                        aControl.Enabled = enable;
                        aControl.Visible = enable;          

                    }
                    else
                    {

                        Control aControl = (Control)ctl;
                        aControl.Enabled = enable;
                        aControl.Visible = enable;          

                    }
                }
            }
            
        }

        /// <summary>
        /// Get the currently selected app from list and return appitem
        /// </summary>
        /// <returns></returns>
        private AppItem GetSelectedApp()
        {
            // 4mar08 new selectedapps
            if (listView2.SelectedItems.Count > 0)
            {
                ListViewItem li = (ListViewItem)listView2.SelectedItems[0];
                SelectedApps sApps= (SelectedApps)li.Tag;
                return data.GetAppItem(sApps.App_Id);
            }
            
            /*
            DataRow dr;
            if (listView2.SelectedItems.Count > 0)
            {
                ListViewItem li = (ListViewItem)listView2.SelectedItems[0];
                dr = (DataRow)li.Tag;
                return dr;
            }
            */
            return null;
        }

        private void PrintInstalledAppInfo(List<InstalledApps.InstalledAppItem> installedApps)
        {
            StringBuilder installInfoStr = new StringBuilder();
            // Get current app
            AppItem Crow = GetSelectedApp();

            // Display Installed Versions
            installInfoStr = new StringBuilder();

            // installed in system
            installInfoStr.Append(string.Format("{0} Details\r\n==========================\r\n\r\n", Crow.AppName));
            if (Crow.Description.Length > 0)
            {
                installInfoStr.Append(Crow.Description + "\r\n");
            }

            installInfoStr.Append(string.Format("Publisher: {0}\r\nLicense: {1}\r\nSystem Requirements: {2}\r\n\r\n",
                Crow.Publisher, Crow.License, Crow.SystemRequirements));

            if (installedApps.Count > 0)
            {
                foreach (InstalledApps.InstalledAppItem ia in installedApps)
                {
                    installInfoStr.Append("Application Name: " + ia.DisplayName
                                        + "\r\nPublisher: " + ia.Publisher
                                        + "\r\nVersion: " + ia.DisplayVersion
                                        + "\r\nInstall date: " + ia.InstallDate.ToShortDateString()
                                        + "\r\nInstall Location: " + ia.InstallLocation + "\r\n\r\n");

                }
            }
            // Display Version Releases
            if (Crow.VersionList.Count>0)
            {
                installInfoStr.Append("\r\n\r\nVersion Releases\r\n");
                installInfoStr.Append("=================\r\n");

                foreach (AppVersion dr in Crow.VersionList)
                {
                    installInfoStr.Append("Version: [" 
                        + dr.VersionNumber + "] - Type: " 
                        + dr.VersionType + "\r\n " + dr.VersionDescription + "\r\n\r\n" );
                }
            }
            

            // txtInfoInstalled.Text = installInfoStr.ToString(); 

            txtInfoBox.Text = installInfoStr.ToString();    
        }

        private void FillVersionSelector()
        {
            cmbVersionSelector.Text = "";
            cmbVersionSelector.Items.Clear();

            SelectedApps sApp = (SelectedApps)listView2.SelectedItems[0].Tag;
            // Get current app
            AppItem Crow = GetSelectedApp();

            try
            {
                foreach (AppVersion dr in Crow.VersionList)
                {
                    string listStr = "v" + dr.VersionNumber + ", " + dr.VersionType;
                    cmbVersionSelector.Items.Add(listStr);
                }
                cmbVersionSelector.SelectedIndex = sApp.SelectedVersionIndex;
            }
            catch { }
        }

        private void FillFilterList()
        {
            cmbFilterList.Items.Clear();
            foreach (string str in data.BuildLicenseList())
            {
                toolStripComboBox1.Items.Add(str);
                cmbFilterList.Items.Add(str);
            }

        }

        private int nIndex=0;

        public object GetCurrentCategory()
        {
            if (listView1.SelectedItems.Count > 0)
            {
                DataRow dr = (DataRow)listView1.SelectedItems[0].Tag;
                if (dr != null)
                {
                    object[] objCat = new object[] { dr["Category_Id"].ToString(), dr["name"].ToString() };
                    return objCat;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        private void FillCategories(DataRowCollection rows)
        {
            listView1.MultiSelect = false;
            // Attach Subitems to the ListView
            listView1.Columns.Add("Category", listView1.Width, HorizontalAlignment.Left);

            listView1.Items.Clear();
            listView1.FullRowSelect = true;
            listView1.HideSelection = false;
            listView1.SmallImageList = imageListCategory;
            listView1.LargeImageList = imageListCategory;
            imageListCategory.ColorDepth = ColorDepth.Depth32Bit;

            // populate all categories
            ListViewItem li1 = new ListViewItem("All Categories");
            listView1.Items.Add(li1);

            // populate categories
            foreach (DataRow dr in rows)
            {
                string Category_Id = dr["Category_Id"].ToString();
                string Category_Name = dr["name"].ToString();
                string IconFile = dr["icon"].ToString();

                // get icon info
                if (IconFile != "")
                {
                    Icon CatIcon = data.GetCatIconFromFile(IconFile);
                    if (CatIcon != null)
                    {
                        imageListCategory.Images.Add(Category_Name, CatIcon);
                    }
                }

                // add icon and text for this item
                ListViewItem li = new ListViewItem(Category_Name);
                
                // li.SubItems.Add(Category_Id);
                li.ImageKey = Category_Name;
                
                li.Tag = (DataRow)dr;
                listView1.Items.Add(li);
            }
        }

        private void BuildAppView()
        {
            listView2.Columns.Add("Name", listView2.Width/4, HorizontalAlignment.Left);
            listView2.Columns.Add("Installed version", listView2.Width/5, HorizontalAlignment.Left);
            listView2.Columns.Add("Current Version", listView2.Width / 5, HorizontalAlignment.Left);

            int tWidth = 0;
            for (int i = 0; i < listView2.Columns.Count; i++)
            {
                tWidth += listView2.Columns[i].Width;
            }
            
            
            listView2.Columns.Add("Description", (listView2.Width-tWidth), HorizontalAlignment.Left);

        }

        /// <summary>
        /// Fill the application list window
        /// </summary>
        private void FillAppList(DataRow[] rows)
        {
            listView2.Items.Clear();

            // add image list for icons
            ImageList iconImages = new ImageList();
            listView2.LargeImageList = iconImages;
            listView2.SmallImageList = iconImages;

            // populate app
            foreach (DataRow dr in rows)
            {
                ListViewItem li = new ListViewItem(dr["name"].ToString());
                // enable separate styles
                li.UseItemStyleForSubItems = false;

                Color rowColor;
                
                if (listView2.Items.Count % 2 == 0)
                {
                    rowColor = Color.White;
                }
                else
                {
                    rowColor = Color.WhiteSmoke;
                }

                li.BackColor = rowColor;

                string App_Id = dr["App_Id"].ToString();



                AppItem app = data.GetAppItem(App_Id);
              

                // locate currently installed app info
                List<InstalledApps.InstalledAppItem> iaList = InstalledApps.FindInstalledApplication(dr["name"].ToString());

                if (iaList.Count > 0)
                {
                    Color InstallDisplayColor;
                    // App is currently installed
                    if (iaList[0].DisplayVersion == "")
                    {
                        // no version number in registry
                        InstallDisplayColor = Color.Orange;
                    }
                    else
                    {
                        if (data.CompareVersion(iaList[0].DisplayVersion,
                                                app.GetLatestVersion().ToString()))
                        {
                            // if newer version available
                            InstallDisplayColor = Color.Red;
                        }
                        else
                        {
                            // Version up to date
                            InstallDisplayColor = Color.Green;
                        }
                    }

                    // Installed Version
                    Color oldColor = li.SubItems[li.SubItems.Count - 1].ForeColor;

                    li.SubItems.Add(iaList[0].DisplayVersion);
                    li.SubItems[li.SubItems.Count - 1].ForeColor = InstallDisplayColor;
                    li.SubItems[li.SubItems.Count - 1].BackColor= rowColor;

                    // li.SubItems[li.SubItems.Count - 1].ForeColor = oldColor;


                    // load icon
                    if (iaList[0].DisplayIcon != null)
                    {
                        iconImages.Images.Add(App_Id, iaList[0].DisplayIcon);
                        li.ImageKey = App_Id;

                    }

                }
                else
                {
                    li.SubItems.Add("-");
                    li.SubItems[li.SubItems.Count - 1].BackColor = rowColor;
                }



                // current latest version
                if (app.VersionList.Count > 0)
                {
                    li.SubItems.Add(app.GetLatestVersion().VersionNumber);
                    li.SubItems[li.SubItems.Count - 1].BackColor = rowColor;
                }


                // description
                li.SubItems.Add(app.Description);
                li.SubItems[li.SubItems.Count - 1].BackColor = rowColor;


                // if in selected applist then check it and set tag
                if (SelectedAppList.ContainsKey(App_Id))
                {
                    li.Checked = true;
                    li.Tag = SelectedAppList[App_Id];
                }
                else
                {
                    // not in selected
                    // 4 mar 08 rob new tag contains selected app id and versionindex
                    li.Tag = new SelectedApps(dr["App_Id"].ToString(), 0);
                }

                listView2.Items.Add(li);
            }
        }


        /// <summary>
        /// refresh the application list
        /// </summary>
        public void RefreshAppList()
        {
            if (listView1.SelectedItems.Count > 0)
            {
                // ClearVersionInfo();

                string Category = listView1.SelectedItems[0].Text.ToString();

                // ALL categories
                if (listView1.SelectedIndices[0] == 0)
                {
                    // all categories
                    FillAppList(data.GetAllApps());
                }
                else
                {
                    // category
                    FillAppList(data.GetAppsByCategory(Category));
                }
                webBrowser1.Stop();
                webBrowser1.DocumentText = Category;
                // webBrowser1.Document.Body.InnerHtml = Category;
            }
        }


        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshAppList();
        }

        private void cmbFilterList_SelectedIndexChanged(object sender, EventArgs e)
        {
            string licenseType = cmbFilterList.Text.ToString();

            FilterByLicense(licenseType);                        
        }

        private void FilterByLicense(string licenseType)
        {
            if (listView1.SelectedItems.Count > 0 && listView1.SelectedIndices[0] != 0)
            {
                string Category = listView1.SelectedItems[0].Text.ToString();

                DataRow dr = (DataRow)listView1.SelectedItems[0].Tag;
                FillAppList(data.GetAppsByLicenseType(licenseType, dr["Category_Id"].ToString()));
            
            }
            else
            {
                // all categories
                FillAppList(data.GetAppsByLicenseType(licenseType));

            }
        }

        private void listView1_SizeChanged(object sender, EventArgs e)
        {
            // listView1.Columns[0].Width = listView1.Width;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            frmImgList fm = new frmImgList();
            fm.Show();
        }

        /// <summary>
        /// Get Information about the current Application
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listView2_SelectedIndexChanged(object sender, EventArgs e)
        {
            // update the view below
            if (listView2.SelectedItems.Count > 0)
            {
                ClearVersionInfo();
                ListViewItem li = (ListViewItem)listView2.SelectedItems[0];
                
                // 4mar08 rob new selected tag replaces datarow
                SelectedApps selectedApp = (SelectedApps)li.Tag;
                //DataRow dr = (DataRow)li.Tag;

                AppItem ai = data.GetAppItem(selectedApp.App_Id);

                // locate currently installed app info
                List<InstalledApps.InstalledAppItem> iaList = InstalledApps.FindInstalledApplication(ai.AppName);
                FillVersionSelector();
                PrintInstalledAppInfo(iaList);

                webBrowser1.Stop();
                webBrowser1.DocumentText = "Loading...";

                // Show content for web browser
                try
                {
                    webBrowser1.Url = new Uri(ai.AppUrl);
                }
                catch
                {
                    webBrowser1.DocumentText = "Unable to load \"" + ai.AppUrl + "\"";
                }

            }
        }

        private void ClearVersionInfo()
        {
            txtInfoBox.Clear();
            
            cmbVersionSelector.Items.Clear();
        }

        private void ShowDownloadManager()
        {
            if (SelectedAppList.Count < 1)
            {
                MessageBox.Show("Nothing to download");
                return;
            }
            
            if (DownloadForm == null || DownloadForm.IsDisposed)
            {
                DownloadForm = new frmDownloadApps();
            }

            // Prepare App List 
            // 04Mar08 rob change to keys
            List<AppItem> apps = new List<AppItem>();
            foreach (SelectedApps sApp in this.SelectedAppList.Values)
            {
                AppItem ai = data.GetAppItem(sApp.App_Id);

                // set version to download
                ai.SelectedVersionIndex = sApp.SelectedVersionIndex;

                // add to list
                apps.Add(ai);
            }


            /*
            foreach (DataRow dr in SelectedAppList.Values)
            {
                apps.Add(data.GetAppItem(dr["App_Id"].ToString()));
            }
             */
            DownloadForm.SetAppsList(apps);
            DownloadForm.Show();

            if (DownloadForm.WindowState == FormWindowState.Minimized)
            {
                DownloadForm.WindowState = FormWindowState.Normal;
            }
            DownloadForm.Focus();


        }


        private void btnDownload_Click(object sender, EventArgs e)
        {
            ShowDownloadManager();

        }

        /// <summary>
        /// Add or Remove an item to selectedappslist
        /// according to selected checkbox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listView2_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
        }

        private void UpdateSelectedAppList()
        {
            foreach (ListViewItem li in listView2.Items)
            {
                SelectedApps sApp = (SelectedApps)li.Tag;
                string App_Id = sApp.App_Id;

                if (li.Checked == true)
                {
                    if (!SelectedAppList.ContainsKey(App_Id))
                    {
                        // add the selected app from listview with current version index to the selected app list
                        SelectedAppList.Add(App_Id, sApp);
                    }
                    else
                    {
                        // update version value with current one
                        SelectedAppList[App_Id].SelectedVersionIndex = sApp.SelectedVersionIndex;
                    }
                }
                else
                {
                    SelectedAppList.Remove(App_Id);
                }
            }
            Console.Write(GetSelectedAppList());
         }


        /// <summary>
        /// loop through list to add / remove items according to checkbox selection
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listView2_Leave(object sender, EventArgs e)
        {
            foreach (ListViewItem li in listView2.Items)
            {
                SelectedApps sApp = (SelectedApps)li.Tag;
                string App_Id = sApp.App_Id;

                if (li.Checked == true)
                {
                    if (!SelectedAppList.ContainsKey(App_Id))
                    {
                        // add the selected app from listview with current version index to the selected app list
                        SelectedAppList.Add(App_Id, sApp);
                    }
                    else
                    {
                        // update version value with current one
                        SelectedAppList[App_Id].SelectedVersionIndex = sApp.SelectedVersionIndex;
                    }
                }
                else
                {
                    SelectedAppList.Remove(App_Id);
                }
            }
            Console.Write(GetSelectedAppList());


        }

        private string GetSelectedAppList()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("SelectedAppList ITEMS\r\n==========================\r\n");
            foreach (string App_Id in SelectedAppList.Keys)
            {
                AppItem ai = data.GetAppItem(App_Id);
                sb.Append(string.Format("[App_Id:{0}] {1}",
                                        ai.App_Id,
                                        ai.AppName) + "\r\n");

            }
            return sb.ToString();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            FillAppList(data.SearchAppsByName(txtSearch.Text));
        }

        private void btnSelectAllApps_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listView2.Items.Count; i++)
            {
                listView2.Items[i].Checked = true;
            }
            listView2.Focus();
        
        }

        /// <summary>
        /// Update whether download button is enabled
        /// </summary>
        private void UpdateDownloadEnabled()
        {
            if (SelectedAppList.Count > 0)
            {
                toolStripBtnDownload.Enabled = true;
            }
            else
            {
                toolStripBtnDownload.Enabled = false;
            }
        }

        private void btnSelectNone_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listView2.Items.Count; i++)
            {
                listView2.Items[i].Checked = false;
            }
            listView2.Focus();
            
        }

        private void btnAddApp_Click(object sender, EventArgs e)
        {
            frmAddApp fa = new frmAddApp(this, this.data);

            if (fa.ShowDialog() == DialogResult.OK)
            {
                // add app to row
                data.AddAppItem(fa.App);
            }
        }


        private void btnAddCategory_Click(object sender, EventArgs e)
        {
            frmEditCategory fe = new frmEditCategory();
            if (fe.ShowDialog() == DialogResult.OK)
            {
                DataRow dr = data.GetCategories().NewRow();
                
                dr["name"] = fe.Category;
                dr["icon"] = System.IO.Path.GetFileName(fe.IconFile);
                // add it to list
                data.GetCategories().Rows.Add(dr);
                
                FillCategories(data.GetCategories().Rows);
                
            }
        }

        private void btnEditCategory_Click(object sender, EventArgs e)
        {
            frmEditCategory fe = new frmEditCategory();
            fe.EditMode = true;
            object[] cat = (object[])GetCurrentCategory();

            fe.Category = (string)cat[1];

            if (fe.ShowDialog() == DialogResult.OK)
            {
                /*
                DataRow[] drs = data.GetCategories().Rows.Select("Category_Id='"+cat[0]+"'");

        
                drs[0]["name"] = fe.Category;
                drs[0]["icon"] = System.IO.Path.GetFileName(fe.IconFile);
                // add it to list

                drs[0].AcceptChanges();

                FillCategories(data.GetCategories().Rows);
                */
            }

        }



        private void cmbVersionSelector_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void cmbVersionSelector_SelectionChangeCommitted(object sender, EventArgs e)
        {
            // set selected index on listview according to this
            ListViewItem li = listView2.SelectedItems[0];
            SelectedApps sApp = (SelectedApps)li.Tag;
            sApp.SelectedVersionIndex = cmbVersionSelector.SelectedIndex;

            li.Tag = sApp;

        }



        private void btnEditItem_Click(object sender, EventArgs e)
        {
            AppItem sApp = GetSelectedApp();
            frmAddApp fa = new frmAddApp(this,data);
            fa.App = sApp;
            if (fa.ShowDialog() == DialogResult.OK)
            {
                // modify this app data
                data.UpdateAppItem(fa.App);
                RefreshAppList();
            }
        }

        private void txtInfoInstalled_TextChanged(object sender, EventArgs e)
        {

        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            data.SaveXML();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmAboutBox abt = new frmAboutBox();
            abt.Show();

        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmOptions fo = new frmOptions();

            if (fo.ShowDialog() == DialogResult.OK)
            {
                // save all settings

            }

        }

        private void debugToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmDebug fd = new frmDebug();
            fd.Show();

        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DownloadApi.Net.DownloadManager.AnyWorkersWorking)
            {
                if (MessageBox.Show("Downloads in progress.\r\nAre you sure you want to exit",
                    "Downloads In Progress", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    return;
                }
            }

            Application.Exit();
        }

        private void eToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            AllowEdit = eToolStripMenuItem.Checked;
            Properties.Settings.Default.Save();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            UpdateSelectedAppList();
            ShowDownloadManager();
        }

        private void toolStripTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                FillAppList(data.SearchAppsByName(toolStripTextBox1.Text));
                e.Handled = true;

            }
        }

        private void toolStripTextBox1_Click(object sender, EventArgs e)
        {

        }

        private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            FilterByLicense(toolStripComboBox1.Text.ToString());
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            frmAddApp fa = new frmAddApp(this, this.data);

            if (fa.ShowDialog() == DialogResult.OK)
            {
                // add app to row
                data.AddAppItem(fa.App);
            }

        }

        private void toolStripBtnEdit_Click(object sender, EventArgs e)
        {
            AppItem sApp = GetSelectedApp();
            frmAddApp fa = new frmAddApp(this, data);
            fa.App = sApp;
            if (fa.ShowDialog() == DialogResult.OK)
            {
                // modify this app data
                data.UpdateAppItem(fa.App);
                RefreshAppList();
            }

        }

        private void btnDeleteApps_Click(object sender, EventArgs e)
        {

        }

        private void listView2_Resize(object sender, EventArgs e)
        {
            // adjust column widths
            // listView2.Columns[0].Width = (listView2.Width / 4);
            // listView2.Columns[1].Width = (listView2.Width / 7);
            // listView2.Columns[2].Width = (listView2.Width / 7);

            int tWidth = 0;
            for (int i = 0; i < listView2.Columns.Count-1; i++)
            {
                tWidth += listView2.Columns[i].Width;
            }

            try
            {
                listView2.Columns[3].Width = (listView2.Width - tWidth);
            }
            catch { }

        }

        private void appContextMenu_Opening(object sender, CancelEventArgs e)
        {
            // fill list with version
            if (listView2.SelectedIndices.Count > 0)
            {
                AppItem app = GetSelectedApp();
                foreach (AppVersion dr in app.VersionList)
                {
                    string listStr = "v" + dr.VersionNumber + ", " + dr.VersionType;
                    appContextMenu.Items.Add(listStr);
                    appContextMenu.Items[appContextMenu.Items.Count - 1].Tag = appContextMenu.Items.Count - 3;
                    // appContextMenu.Items[appContextMenu.Items.Count -1 ]
                }
 
            }
        }

        private void appContextMenu_Closed(object sender, ToolStripDropDownClosedEventArgs e)
        {
            // clear items whose Tag is not set, or is false
            // remove items counting down
            for (int i = appContextMenu.Items.Count-1; i > 1; i--)
            {
                appContextMenu.Items.RemoveAt(i);
            }
            

        }

        private void appContextMenu_Opened(object sender, EventArgs e)
        {

        }

        private void appContextMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Tag != null && e.ClickedItem.Tag != "")
            {
                // set selected index on listview according to this
                ListViewItem li = listView2.SelectedItems[0];
                SelectedApps sApp = (SelectedApps)li.Tag;
                sApp.SelectedVersionIndex = (int)e.ClickedItem.Tag;

                li.Tag = sApp;
            }
        }

        private const string _VERSIONURL = "http://122.106.92.33:81/appupdates/appbrowser/versions.txt";
        
        /// <summary>
        /// Check for updates
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkNewVerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            /*
            frmDownloadUpdates dl = new frmDownloadUpdates();
            dl.data = this.data;
            dl.UpdateUrl = _VERSIONURL;
            dl.Show();
        */
        }


        private DateTime ConvertFromUniversalDate(string UniversalDate)
        {
            string[] pieces = UniversalDate.Split('-');
            DateTime dt = new DateTime(Convert.ToInt32(pieces[0]), Convert.ToInt32(pieces[1]), Convert.ToInt32(pieces[2]));
            return dt;
        }
    }
}
